package top.lingchen.blogapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.lingchen.blogapi.bean.Category;
import top.lingchen.blogapi.mapper.CategoryMapper;
import top.lingchen.blogapi.service.CategoryService;
import top.lingchen.blogapi.vo.CategoryVo;
import top.lingchen.blogapi.vo.Result;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author 凌宸
 * @create 2021-12-17 下午 1:59
 * @Description
 * @Version 1.0
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public CategoryVo findCategoryById(Long categoryId) {
        Category category = categoryMapper.selectById(categoryId);
        CategoryVo categoryVo = new CategoryVo();
        BeanUtils.copyProperties(category, categoryVo);
        return categoryVo;
    }

    @Override
    public Result findAll() {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Category::getId, Category::getCategoryName);
        List<Category> categories = categoryMapper.selectList(wrapper);
        return Result.success(copyList(categories));
    }

    @Override
    public Result findAllCategoryDetail() {
        List<Category> categories = categoryMapper.selectList(null);
        return Result.success(copyList(categories));
    }

    @Override
    public Result findCategoryDetailById(Long categoryId) {
        return Result.success(copy(categoryMapper.selectById(categoryId)));
    }

    private List<CategoryVo> copyList(List<Category> categories) {
        List<CategoryVo> categoryVoList = new ArrayList<>();
        for (Category category : categories) {
            categoryVoList.add(copy(category));
        }
        return categoryVoList;
    }

    private CategoryVo copy(Category category) {
        CategoryVo categoryVo = new CategoryVo();
        BeanUtils.copyProperties(category, categoryVo);
        categoryVo.setId(String.valueOf(category.getId()));
        return categoryVo;
    }


}
